//
//  vhECGAnalysisObject.m
//  vhECGSDKAnalysis
//
//  Created by Han Mingjie on 2021/3/6.
//

#import "vhECGAnalysisObject.h"
#import <vhEcgServiceRest/vhEcgServiceRest-Swift.h>
#import <vhECGCodes/vhECGCodes.h>

@implementation vhECGAnalysisObject
@synthesize ECGsArray,ecgRate,patientAge,patientGender;
@synthesize templateAnalysisResult,parametersResult,measurementsResult;
@synthesize minnesotaCodes;
@synthesize interpretation;
@synthesize beatPositions;
@synthesize RRs;

-(id)init{
//    NSDateFormatter *df = [[NSDateFormatter alloc] init];
//    [df setTimeZone:[NSTimeZone systemTimeZone]];
//    [df setLocale:[NSLocale systemLocale]];
//    [df setDateFormat:@"yyyyMMdd"];
//    NSString *today = [df stringFromDate:[NSDate date]];
//    if ([today integerValue] > 20250624){//20240331
//        NSLog(@"vhECGAnalysisObject.framework has Expired!");
//        return nil;
//    }
//    NSLog(@"Warning: This vhECGAnalysisObject.framework will expired: 20250624");
    self = [super init];
    if (self){
        NSLog(@"Welcome vhECGSDKAnalysis Version: %.2f is ready.\n", vhECGSDKAnalysisVersionNumber);
    }
    return self;
}

-(BOOL)analysisECG:(NSArray <NSArray <NSNumber *>*>*)inECGsArray withRate:(NSInteger)inECGRate withPatientAge:(NSInteger)inAge withPatientGender:(vhECGPatientGender)inGender{
    if (nil == inECGsArray){
        NSLog(@"ECGsArray can NOT be nil.");
        return NO;
    }
    if (![inECGsArray isKindOfClass:[NSArray class]]){
        NSLog(@"ECGsArray is not NSArray class.");
        return NO;
    }
    if (inECGsArray.count != 12){
        NSLog(@"ECGsArray must include 12 subarray for every lead.");
        return NO;
    }
    if (inECGRate < 300){
        NSLog(@"ecgRate failed.");
        return NO;
    }
    if (inECGsArray.firstObject.count/inECGRate < 10){
        NSLog(@"ECG's len less than 10 seconds.");
        return NO;
    }
    Analyzer *analyzer = [[Analyzer alloc] init];
    NSString *sex = @"m";
    switch (inGender) {
        case vhECGPatientGender_Male:
            sex = @"m";
            break;
        case vhECGPatientGender_Female:
            sex = @"f";
            break;
        case vhECGPatientGender_Unknow:
            sex = @"m";
            break;
        default:
            break;
    }
    ECGsArray = inECGsArray;
    ecgRate = inECGRate;
    patientAge = inAge;
    patientGender = inGender;
    
    AnalysisResult *result = [analyzer analyzeWithData:ECGsArray sampling:ecgRate age:patientAge ageUnit:@"y" gender:sex newBornMode:0 backRecording:0];
    
    minnesotaCodes = [NSArray arrayWithArray:result.minnesotaCodes];
    
    vhECGCodes *code = vhECGCodes.shareCodeExchange;
    NSMutableArray *aaa = [[NSMutableArray alloc] init];
    for (NSNumber *num in result.autoInterpretationCodes){
        //got string from code.
        NSString *ss = [code stringForCode:[num integerValue]];
        [aaa addObject:ss];
    }
    interpretation = [NSArray arrayWithArray:aaa];
    
    templateAnalysisResult = [[vhMutableTemplateAnalysis  alloc] initWithArray:result.onoff curveTemplate:result.template_];
    parametersResult = [[vhMutableParameters alloc] initWithString:result.parameters];
    measurementsResult = [[vhMutableMeasurements alloc] initWithArray:result.measurement];
    
    beatPositions = [NSArray arrayWithArray:result.beatPositions];
    RRs = [NSArray arrayWithArray:result.RRs];
    return YES;
}

-(BOOL)manualAnalisysLead:(vhLeadTemplate *)targetLead{
    short **onOffs = nil;
    onOffs = malloc(12 *  sizeof(short *));
    for (int i=0;i<12;i++){
        onOffs[i] = malloc(6 * sizeof(short));
    }
    NSArray *leadsArray = [templateAnalysisResult leadsTemplateAnalisysArray];
    NSInteger lead = -1;
    for (int i=0;i<12;i++){
        vhLeadTemplate *leadTemplate = [leadsArray objectAtIndex:i];
        if (nil == leadTemplate){
            NSLog(@"vhLeadTemplate is nil, can NOT manualAnalisysLead complete.");
            return NO;
        }
        if (leadTemplate == targetLead){
            lead = i;
        }
        onOffs[i][0] = (short)leadTemplate.Pb;
        onOffs[i][1] = (short)leadTemplate.Pe;
        onOffs[i][2] = (short)leadTemplate.QRSb;
        onOffs[i][3] = (short)leadTemplate.QRSe;
        onOffs[i][4] = (short)leadTemplate.Tb;
        onOffs[i][5] = (short)leadTemplate.Te;
    }
    BOOL result = NO;
    if(lead >= 0) {
        result = [self manualAnalysisAllLead:nil lead:lead onOffs:onOffs];
    }
    else {
        NSLog(@"Error: target Lead NOT found.");
    }
    for (int i=0;i<12;i++) {
        free(onOffs[i]);
    }
    free(onOffs);
    return result;
}

-(BOOL)manualAnalysisAllLead{
    if (nil == templateAnalysisResult){
        NSLog(@"templateAnalysisResult is nil, can NOT manualAnalysisAllLeadWithECGs complete.");
        return NO;
    }
    short *onOff = nil;
    onOff = malloc(6 * sizeof(short));
    onOff[0] = (short)templateAnalysisResult.Pb;
    onOff[1] = (short)templateAnalysisResult.Pe;
    onOff[2] = (short)templateAnalysisResult.QRSb;
    onOff[3] = (short)templateAnalysisResult.QRSe;
    onOff[4] = (short)templateAnalysisResult.Tb;
    onOff[5] = (short)templateAnalysisResult.Te;
    BOOL result = [self manualAnalysisAllLead:onOff lead:-1 onOffs:nil];
    free(onOff);
    return result;
}


-(BOOL)manualAnalysisAllLead:(int16_t * _Nullable)onOff lead:(NSInteger)lead onOffs:(int16_t * _Nullable * _Nullable)onOffs{
    Analyzer *analyzer = [[Analyzer alloc] init];
    NSString *sex = @"m";
    switch (patientGender) {
        case vhECGPatientGender_Male:
            sex = @"m";
            break;
        case vhECGPatientGender_Female:
            sex = @"f";
            break;
        case vhECGPatientGender_Unknow:
            sex = @"m";
            break;
        default:
            break;
    }
    AnalysisResult *result = [analyzer analyzeManualWithData:ECGsArray sampling:ecgRate age:patientAge ageUnit:@"y" gender:sex newBornMode:0 backRecording:0 lead:lead onOff:onOff onOffs:onOffs];
    
    minnesotaCodes = [NSArray arrayWithArray:result.minnesotaCodes];

    vhECGCodes *code = vhECGCodes.shareCodeExchange;
    NSMutableArray *aaa = [[NSMutableArray alloc] init];
    for (NSNumber *num in result.autoInterpretationCodes){
        //got string from code.
        NSString *ss = [code stringForCode:[num integerValue]];
        [aaa addObject:ss];
    }
    interpretation = [NSArray arrayWithArray:aaa];
    
    templateAnalysisResult = [[vhMutableTemplateAnalysis alloc] initWithManualArray:result.onoff];
    parametersResult = [[vhMutableParameters alloc] initWithString:result.parameters];
    measurementsResult = [[vhMutableMeasurements alloc] initWithArray:result.measurement];
    
    beatPositions = [NSArray arrayWithArray:result.beatPositions];
    RRs = [NSArray arrayWithArray:result.RRs];
    return YES;
}
@end
